package com.atguigu.lease.web.admin.controller.apartment;

import com.atguigu.lease.common.result.Result;
import com.atguigu.lease.module.entity.AttrKey;
import com.atguigu.lease.module.entity.AttrValue;
import com.atguigu.lease.web.admin.service.AttrKeyService;
import com.atguigu.lease.web.admin.service.AttrValueService;
import com.atguigu.lease.web.admin.vo.attr.AttrKeyVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/admin/attr")
@Tag(name = "房间属性管理",description = "attrController")
public class AttrController {
    @Autowired
    private AttrKeyService attrKeyService;




    @Autowired
    private AttrValueService attrValueService;

    @GetMapping("list")
    @Operation(summary = "查询全部属性名和属性值")
    public Result<List<AttrKeyVo>> getList(){
     //  List<AttrKeyVo>attrKeyVoList = attrKeyService.getAttrKeyVoList();
     //  return Result.ok(attrKeyVoList);

       //方式2：不需要写sql语句
        //2.1 先获取所有的键 然后根据键获取值
        List<AttrKey> attrKeyList = attrKeyService.list();
        List<AttrKeyVo> attrKeyVoList = new ArrayList<>();
        attrKeyList.forEach(attrKey -> {
            List<AttrValue> attrValueList = attrValueService.list(new LambdaQueryWrapper<AttrValue>().eq(AttrValue::getAttrKeyId, attrKey.getId()));
            AttrKeyVo attrKeyVo = new AttrKeyVo();
            BeanUtils.copyProperties(attrKey,attrKeyVo);
            attrKeyVo.setAttrValueList(attrValueList);
            attrKeyVoList.add(attrKeyVo);

        });
        return Result.ok(attrKeyVoList);
    }

    @PostMapping("key/saveOrUpdate")
    @Operation(summary = "更新或添加属性名")
    public Result saveOrUpdateKey(@RequestBody AttrKey attrKey){
        attrKeyService.saveOrUpdate(attrKey);
        return Result.ok();
    }

    @PostMapping("value/saveOrUpdate")
    @Operation(summary = "更新或添加属性值")
    public Result saveOrUpdateValue(@RequestBody AttrValue attrValue){
        attrValueService.saveOrUpdate(attrValue);
        return Result.ok();
    }

    @DeleteMapping("key/deleteById")
    @Operation(summary = "根据id删除属性名")
    public Result deleteKeyById(@RequestParam Long id){
        attrKeyService.removeById(id);
        LambdaQueryWrapper<AttrValue>lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(AttrValue::getAttrKeyId,id);
        attrValueService.remove(lambdaQueryWrapper);
        return Result.ok();
    }

    @DeleteMapping("value/deleteById")
    @Operation(summary = "根据id删除属性值")
    public Result deleteValueById(@RequestParam Long id){
        attrValueService.removeById(id);
        return Result.ok();
    }



}
